import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:netease_music/main.dart';
import 'package:netease_music/netService.dart';
import 'package:provider/provider.dart';

class TopicUiPlayListProvider extends ChangeNotifier {
  final List<Topic> _list = [];
  bool _hover = false;
  int _hoverIndex = -1;

  int get hoverIndex => _hoverIndex;

  bool get hover => _hover;

  void updateHoverStatus(bool status, int index) {
    _hover = status;
    _hoverIndex = index;
    notifyListeners();
  }

  List<Topic> get list => _list;

  void updateList(List<Topic> l) {
    _list.clear();
    _list.addAll(l);
    notifyListeners();
  }
}

class TopicUi extends StatefulWidget {
  final String path;

  const TopicUi(this.path, {super.key});

  @override
  State<TopicUi> createState() => _TopicUiState();
}

class _TopicUiState extends State<TopicUi> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Center(
        child: Wrap(
          runSpacing: 20,
          spacing: 20,
          children: [
            ...List.generate(
                context.watch<TopicUiPlayListProvider>().list.length, (i) {
              return TopicItem(
                index: i,
              );
            })
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _loadResource();
  }

  Future<void> _loadResource() async {
    List<Topic> topicList = await globalServie.playlist(widget.path);
    context.read<TopicUiPlayListProvider>().updateList(topicList);
  }
}

class TopicItem extends StatelessWidget {
  final int index;

  const TopicItem({super.key, required this.index});

  @override
  Widget build(BuildContext context) {
    var provider = context.read<TopicUiPlayListProvider>();
    List<Topic> list = provider.list;
    return MouseRegion(
      onEnter: (_) {
        provider.updateHoverStatus(true, index);
      },
      onExit: (_) {
        provider.updateHoverStatus(false, index);
      },
      child: Stack(
        children: [
          SizedBox(
            width: 180,
            height: 180,
            child: GestureDetector(
              onTap: () {
                context.push('/detail', extra: list[index].playId);
              },
              child: BackgroundPart(index),
            ),
          ),
          TitlePart(index),
        ],
      ),
    );
  }
}

class TitlePart extends StatelessWidget {
  final int index;

  const TitlePart(this.index, {super.key});

  @override
  Widget build(BuildContext context) {
    var providerw = context.watch<TopicUiPlayListProvider>();
    var provider = context.read<TopicUiPlayListProvider>();
    List<Topic> list = provider.list;
    return Positioned(
      left: providerw.hover && providerw.hoverIndex == index ? 0 : 10,
      bottom: 0,
      right: providerw.hover && providerw.hoverIndex == index ? 0 : 10,
      child: AnimatedContainer(
        clipBehavior: Clip.hardEdge,
        height: providerw.hover && providerw.hoverIndex == index ? 90 : 50,
        duration: const Duration(milliseconds: 200),
        decoration: BoxDecoration(
          color: const Color.fromRGBO(48, 87, 150, 1).withOpacity(0.5),
          shape: BoxShape.rectangle,
          boxShadow: [
            BoxShadow(
              color: const Color.fromRGBO(48, 87, 150, 1),
              blurRadius:
                  providerw.hover && providerw.hoverIndex == index ? 20 : 5,
              blurStyle: BlurStyle.outer,
              spreadRadius: 1,
            )
          ],
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 5),
          child: Center(
            child: Text(
              list[index].topicName,
              style: TextStyle(foreground: Paint()..color = Colors.white),
            ),
          ),
        ),
      ),
    );
  }
}

class BackgroundPart extends StatelessWidget {
  final int index;

  const BackgroundPart(this.index, {super.key});

  @override
  Widget build(BuildContext context) {
    var providerw = context.watch<TopicUiPlayListProvider>();
    var provider = context.read<TopicUiPlayListProvider>();
    List<Topic> list = provider.list;

    return Column(
      children: [
        AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          width: providerw.hover && providerw.hoverIndex == index ? 180 : 160,
          height: providerw.hover && providerw.hoverIndex == index ? 180 : 160,
          decoration: BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.cover,
              image: NetworkImage('${list[index].topicPicUrl}?param=80y80'),
            ),
          ),
        ),
      ],
    );
  }
}

class TodayPlayListUi extends StatefulWidget {
  const TodayPlayListUi({super.key});

  @override
  State<StatefulWidget> createState() {
    return _TodayPlayListUi();
  }
}

class _TodayPlayListUi extends State<TodayPlayListUi> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        IconButton(
            onPressed: () {
              context.pop();
            },
            icon: const Icon(Icons.keyboard_arrow_left_outlined)),
        Expanded(
          child: ListView.builder(
            itemBuilder: (c, i) {
              return PlayListUi(i);
            },
            itemCount: context.watch<CurrentProvider>().playItemList.length,
          ),
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    _loadResource();
  }

  Future<void> _loadResource() async {
    try {
      List<PlayItem> items = await globalServie.recommend();
      Provider.of<CurrentProvider>(context, listen: false)
          .updatePlayItemList(items);
    } catch (e) {
      print(e);
    }
  }
}

class Topic {
  String topicName;
  String topicPicUrl;
  int playId;

  Topic(
      {required this.topicName,
      required this.topicPicUrl,
      required this.playId});
}